/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.amazon.file.reader;

import com.amazon.line.parser.CommandParser;
import java.io.*;

/**
 *
 * @author Salman Noor, Shcool of Electrical and Information Engineering
 * @Copyright: Wits University 2013 - All Rights Reserved @email
 * salmannoor74415@gmail.com @License BSD License
 * (http://www.linfo.org/bsdlicense.html)
 */
public class CommandFileReader {

    private static CommandFileReader instance = null;

    private CommandFileReader() {
        //to defeat instantiation
    }

    public static CommandFileReader getInstance() {
        if (instance == null) {
            instance = new CommandFileReader();
        }
        return instance;
    }

    public int readFile(String consoleInput) throws IOException {
        if (consoleInput.equalsIgnoreCase("--exit") || consoleInput.equalsIgnoreCase("exit")) {
            System.out.println("Thank for using Amazon File Reader. Bye");
            return 0;
        } else if (consoleInput.equalsIgnoreCase("--help") || consoleInput.equalsIgnoreCase("help")) {
            System.out.println("Please enter a valid text file in a valid location.");
            System.out.println("Operations allowed : SUM AVERAGE MIN MAX");
            System.out.println("Command Line Format Allowed : eg . SUM : 1, 4,5,5,6");
            System.out.println("No negetive numbers allowed");
            System.out.println("No decimal numbers allowed");
            System.out.println("Enter 'exit' to exit the program");

        } else if (!consoleInput.isEmpty()) {
            BufferedReader br = null;
            try {
                File theTextFile = new File(consoleInput);
                br = new BufferedReader(new FileReader(theTextFile));
                this.acceptTxtFile(consoleInput);
            } catch (InvalidFileFormatException ex) {
                System.err.println(ex.getMessage());
                return 1;
            } catch (FileNotFoundException ex) {
                System.err.println(ex.getMessage());
                return 1;
            }


            String commandline = "";
            int lineNumber = 0;
            while ((commandline = br.readLine()) != null) {
                // process the line.
                CommandParser CP = new CommandParser(commandline, lineNumber);
                CP.ParseAndExecuteLine();
                lineNumber++;
            }
            br.close();

        }
        return 1;
    }

    private boolean acceptTxtFile(String fileName) throws InvalidFileFormatException {
        boolean accept = fileName.endsWith(".txt");

        if (!accept) {
            throw new InvalidFileFormatException(fileName + " format is invalid. Only text files are allowed.");
        }
        return accept;
    }
}
